<!doctype html>

<html>
    
<head>
    <meta charset="utf-8">
    <meta name="keywords" content="">
    <meta name="description" content="">
    <title>登录</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        form {
            width: 500px;
            margin: 100px auto;
            padding: 10px;
            padding-top: 40px;
            font-size: 20px;
            line-height: 20px;
            border: 2px solid plum;
            display: flex;
            flex-direction: column;
            position: relative;
        }

        form > span {
            position: absolute;
            top: 10px;
            left: 50%;
            width: 100%;
            transform: translateX(-50%);
            text-align: center;
            color: red;
            display: none ;
        } 

        form label {
            text-align: center;
        }

        form label input {
            margin-bottom: 10px;
            font-size: 20px;
            text-align: center;
        }
    </style>
</head>

<body>
    <form action="" method="">
        <span class="error">用户名或者密码错误</span>
        <label for="">
            账号：<input type="text" class="username"> 
        </label>
        <label for="">
            密码：<input type="text" class="password">
        </label>
        <button>登录</button>
    </form>

    <script>
        // 0 获取元素
        var form = document.querySelector('form');
        var username = document.querySelector('.username');
        var password = document.querySelector('.password');
        var error = document.querySelector('.error');
        // 1 给表单绑定事件
        form.onsubmit = function (e) {
            e.preventDefault();
            // 2 获取输入内容
            var name = username.value;
            var pwd = password.value;
            // 2-2判断用户名与密码
            if (!name || !pwd) return alert('请填写完整表单');
            // 3 发送ajax请求
            var xhr = new XMLHttpRequest();
            xhr.open('post', 'http://localhost:8888/users/login', true);
            xhr.onload = function () {
                // 解析后端json格式
                var res = JSON.parse(xhr.responseText); 
                // 进行条件判断
                if (code === 0) {
                    error.style.display = block
                } else {
                    window.location.href = 'www.baidu.com'
                }
            }
            // 因为是post请求，需要做特殊说明
            xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
            // 参数写在最后
            xhr.send('username=' + name + '&password=' + pwd);  
                 
        }
    </script>
</body>

</html>